import mqtt from "mqtt/dist/mqtt.js";
import store from "../store";

function connectMqtt(HOST, CLIENT_ID, {
	success,
	fail
}) {
	console.log(HOST, CLIENT_ID);
	let client = null;
	// #ifdef H5
	client = mqtt.connect(`ws://${HOST}:8083/mqtt`, {
		clientId: CLIENT_ID,
		qos: 0,
		clean: true,
		username: "sf_app",
		password: "giftwl12",
	});
	// #endif
	// #ifdef MP-WEIXIN||APP
	client = mqtt.connect(`wx://${HOST}:8083/mqtt`, {
		clientId: CLIENT_ID,
		qos: 0,
		clean: true,
		username: "sf_app",
		password: "giftwl12",
	});
	// #endif

	client.on("connect", () => {
		console.log("MQTT Connected");
		success(client);
	});

	client.on("error", (error) => {
		console.error("MQTT Error:", error);
		client = null;
		fail(error);
	});

	// 连接断开后触发的回调
	client.on("close", function() {
		console.log("已断开连接");
	});

	client.on("error", (error) => {
		console.error("MQTT Error:", error);
		client = null;
		fail(error);
	});

	// 连接断开后触发的回调
	client.on("close", function() {
		console.log("已断开连接");
	});

	client.on("message", (topic, message) => {
		let getMsg = JSON.parse(message);
		console.log("topic, getMsg", topic, getMsg);
		if (getMsg.todo == "takePhoto") {
			uni.$emit("takePhoto", topic, getMsg.data);
		} else if (getMsg.todo == "takeAudio") {
			uni.$emit("takeAudio", topic, getMsg.data);
		} else if (getMsg.todo == "takeTrtc") {
			uni.$emit("takeTrtc", getMsg);
		} else if (getMsg.todo == "linkTrtc") {
			uni.$emit("linkTrtc", getMsg.data);
		} else if (getMsg.todo == "refresh_photo") {
			uni.$emit("refresh_photo", getMsg);
		} else if (getMsg.todo == "refresh_audio") {
			uni.$emit("refresh_audio", getMsg);
		} else if (getMsg.todo == "add_friend") {
			uni.$emit("add_friend", getMsg.data);
		} else if (getMsg.todo == "sos") {
			uni.$emit("showError", getMsg.data);
		} else if (getMsg.todo == "danger_alarm") {
			uni.$emit("danger_alarm", getMsg.data);
		}
	});
}

export default connectMqtt;